package cn.yunhe.java.security.filter;

import cn.yunhe.java.security.exception.VerifyCodeException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

public class VerificationCodeFilter extends OncePerRequestFilter {

    private AuthenticationFailureHandler authenticationFailureHandler = new AuthenticationFailureHandler() {
        @Override
        public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                            AuthenticationException exception) throws IOException, ServletException {
           //前后端分离项目
//            response.setContentType("application/json;charset=utf-8");
//            PrintWriter out = response.getWriter();
//            out.println("{\"code\":300,\"message\":\"验证码错误！\"}");
//            out.flush();
            //非前后端分离项目
            request.getRequestDispatcher("/login/index").forward(request,response);
            request.getSession().setAttribute("SPRING_SECURITY_LAST_EXCEPTION",exception);
        }
    };

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取uri   /ssm/hzn
        String uri = request.getRequestURI().replace(request.getContextPath(),"");
        if(!"/hzn".equals(uri)){
            filterChain.doFilter(request,response);
        }else{
            try {
                verificationCode(request);
                filterChain.doFilter(request, response);
            }catch(VerifyCodeException e){
               // e.printStackTrace();
                authenticationFailureHandler.onAuthenticationFailure(request,response,e);
            }
        }
    }

    private void verificationCode(HttpServletRequest request) {
        String reqCode = request.getParameter("verifyCode");
        HttpSession session = request.getSession();
        String sessionCode = (String) session.getAttribute("verifyCode");
        //清除session中的验证码
        if(!StringUtils.isEmpty(sessionCode)){
            session.removeAttribute("verifyCode");
        }

        if(!reqCode.equalsIgnoreCase(sessionCode)){
             throw  new VerifyCodeException("验证码错误！");
        }
    }
}
